package gttp.nspa.client.adm.ui;

import gttp.nspa.client.adm.Dict;
import gttp.nspa.shared.om.IEntity;
import gttp.nspa.shared.om.Locker;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.editor.client.Editor.Path;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.widget.client.TextButton;
import com.sencha.gxt.core.client.Style.SelectionMode;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.data.shared.PropertyAccess;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.FramedPanel;
import com.sencha.gxt.widget.core.client.ListView;

public class SelectEntityForm<T extends IEntity> implements IsWidget {

    interface EntityProps extends PropertyAccess {

        @Path("code")
        ModelKeyProvider<IEntity> key();

        ValueProvider<IEntity, IEntity> self();
    }

    protected String       caption;
    protected int          formWidth;
    protected int          labelWidth;

    protected TextButton   btnOk;
    protected TextButton   btnCancel;

    protected ContentPanel pane;

    private ListStore      entStore;
    private ListView       entView;

    public SelectEntityForm(String caption, int formWidth, int labelWidth) {
        this.caption = caption;
        this.formWidth = formWidth;
        this.labelWidth = labelWidth;

        init();
    }

    private void init() {
        pane = createContentPane(caption, formWidth);

        EntityProps props = GWT.create(EntityProps.class);

        entStore = new ListStore<>(props.key());
        entStore.addAll(Dict.LOCKER.listOccupied(false));
        entView = new ListView(entStore, props.self());
        entView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        entView.setCell(new AbstractCell<Locker>() {

            public void render(Context context, Locker value, SafeHtmlBuilder sb) {
                sb.appendHtmlConstant(value.getName());
            }
        });
        pane.add(entView);

        btnOk = new TextButton("Ok");
        btnCancel = new TextButton("Cancel");
        pane.addButton(btnOk);
        pane.addButton(btnCancel);
    }

    public Widget asWidget() {
        return pane;
    }

    protected ContentPanel createContentPane(String caption, int width) {
        FramedPanel pane = new FramedPanel();
        pane.setHeadingText(caption);
        pane.setWidth(width);
        pane.setBodyStyle("background: none; padding: 5px");
        return pane;
    }
}
